import React, { useState, useRef } from 'react';
import { Form, Input, Button, Toast, Radio, Space, Dialog } from 'antd-mobile';
import { EyeInvisibleOutline, EyeOutline } from 'antd-mobile-icons'
import '../pagessass/Layout.scss';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import AnimatedTransition from '../AnimatedTransition';

const PHONE_REGEX = /^1[3-9]\d{9}$/;
const PASSWORD_REGEX = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
const CODE_REGEX = /^\d{6}$/;

const Layout: React.FC = () => {
    const [phone, setPhone] = useState('');
    const [password, setPassword] = useState('');
    const [code, setCode] = useState('');
    const [countdown, setCountdown] = useState(0);
    const [role, setRole] = useState<'user' | 'admin' | 'aaa'>('user');
    const timerRef = useRef<number | null>(null);
    const navigate = useNavigate();
    const [visible, setVisible] = useState(false)

    const handleGetCode = () => {
        if (!PHONE_REGEX.test(phone)) {
            Toast.show({ content: '请输入正确的手机号' });
            return;
        }
        Toast.show({ content: '验证码已发送' });
        setCountdown(60);
        timerRef.current = window.setInterval(() => {
            setCountdown(prev => {
                if (prev <= 1) {
                    clearInterval(timerRef.current!);
                    return 0;
                }
                return prev - 1;
            });
        }, 1000);
    };

    const handleRoleChange = (value: 'user' | 'admin' | 'aaa') => {
        setRole(value);
        if (value === 'admin') {
            Dialog.show({
                content: '您选择了管理员身份，请确保您有管理员权限！',
                closeOnAction: true,
                actions: [
                    { key: 'ok', text: '知道了' }
                ]
            });
        } else if (value === 'aaa') {
            Dialog.show({
                content: '您选择了超级管理员身份，请确保您有超级管理员权限！',
                closeOnAction: true,
                actions: [
                    { key: 'ok', text: '知道了' }
                ]
            });
        }
    };

    const handleSubmit = () => {
        if (!PHONE_REGEX.test(phone)) {
            Toast.show({ content: '请输入正确的手机号' });
            return;
        }
        if (!PASSWORD_REGEX.test(password)) {
            Toast.show({ content: '密码至少8位，需包含字母和数字' });
            return;
        }
        if (!CODE_REGEX.test(code)) {
            Toast.show({ content: '请输入6位验证码' });
            return;
        }
        Toast.show({ content: '正在注册...' });
        try {
            // 调用后端注册接口
            axios.post('http://localhost:4000/zhuce', {
                phone,
                password,
                role
            }).then(res => {
                // 根据后端返回码处理结果
                if (res.data.code === 409) {
                    alert('该手机号已被注册')
                } else if (res.data.code === 200) {
                    alert('注册成功')
                    navigate('/');
                } else {
                    alert('注册失败')
                }
            })

        } catch {
            Toast.show({ content: '网络错误，请稍后重试' });
        }
    };

    return (
        <AnimatedTransition>
            <div className="register-page">
                <div className="register-box">
                    <div className="header">
                        <h1>账号注册</h1>
                        <p>创建新账号，开启精彩旅程</p>
                    </div>
                    <Form layout="horizontal" footer={
                        <Button block color="primary" onClick={handleSubmit}>注册</Button>
                    }>
                        <Form.Item label="手机号" name="phone">
                            <Input
                                placeholder="请输入手机号"
                                value={phone}
                                onChange={setPhone}
                                clearable
                            />
                        </Form.Item>
                        <Form.Item
                            label='设置密码'
                            name='password'
                            extra={
                                <div className="eye">
                                    {!visible ? (
                                        <EyeInvisibleOutline onClick={() => setVisible(true)} />
                                    ) : (
                                        <EyeOutline onClick={() => setVisible(false)} />
                                    )}
                                </div>
                            }
                        >
                            <Input
                                placeholder='请设置密码'
                                value={password}
                                onChange={setPassword}
                                clearable
                                type={visible ? 'text' : 'password'}
                            />
                        </Form.Item>
                        <Form.Item
                            label="验证码"
                            name="code"
                            extra={
                                <Button
                                    size="small"
                                    color="primary"
                                    disabled={countdown > 0}
                                    onClick={handleGetCode}
                                >
                                    {countdown > 0 ? `${countdown}s` : '获取验证码'}
                                </Button>
                            }
                        >
                            <Input
                                placeholder="请输入验证码"
                                value={code}
                                onChange={setCode}
                                clearable
                            />
                        </Form.Item>
                        {/* 单选角色选择 */}
                        <Form.Item label="角色" name="role">
                            <Space>
                                <Radio checked={role === 'user'} onChange={() => handleRoleChange('user')}>用户</Radio>
                                <Radio
                                    checked={role === 'admin'}
                                    onChange={() => {
                                        setRole('admin');
                                        Dialog.show({
                                            content: (
                                                <div>
                                                    <div>您选择了<strong>管理员</strong>身份。</div>
                                                    <div style={{ marginTop: 8, color: '#888' }}>请确保您有管理员权限，否则无法正常使用相关功能。</div>
                                                </div>
                                            ),
                                            closeOnAction: true,
                                            actions: [
                                                { key: 'ok', text: '明白了' }
                                            ]
                                        });
                                    }}
                                >
                                    管理员
                                </Radio>
                                <Radio checked={role === 'aaa'}
                                    onChange={() => {
                                        setRole('aaa');
                                        Dialog.show({
                                            content: (
                                                <div>
                                                    <div>您选择了<strong>管理员</strong>身份。</div>
                                                    <div style={{ marginTop: 8, color: '#888' }}>您选择了超级管理员身份，请确保您有超级管理员权限！</div>
                                                </div>
                                            ),
                                            closeOnAction: true,
                                            actions: [
                                                { key: 'ok', text: '明白了' }
                                            ]
                                        });
                                    }}>CEO</Radio>
                            </Space>
                        </Form.Item>
                    </Form>
                </div>
            </div>
        </AnimatedTransition>
    );
};

export default Layout;
